<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\ProjectLockPerOrg;
//use app\api\model\ProjectLockPerOrgPeople;
use app\api\model\ProjectPerformance as ProjectPerformanceModel;
use app\api\model\ProjectPerformanceClass;
use app\api\model\ProjectPerformanceSpot;
use app\api\model\ProjectPerOrg as ProjectPerOrgModel;
use app\api\model\ProjectPerOrg;
//use app\api\model\ProjectPerOrgPeople;
use app\api\model\ProjectReviewResult;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use app\api\model\ProjectLockPerformanceClass;
use app\api\model\ProjectLockPerformanceSpot;
use app\api\model\ProjectLockReviewResult;

use think\facade\Config;
use think\facade\View;
use think\facade\Db;

class Base extends BaseController
{
    //封装模板渲染函数
    public function fetch($tpl = "")
    {
        if ($tpl) {
            return View::fetch($tpl);
        } else {
            return View::fetch();
        }
    }

    //封装模型变量输出
    public function assign($name, $data)
    {

        return View::assign($name, $data);

    }

    //门户token验证
    public function checktoken($token = "")
    {

        $uuid = uuid();
        $arr = array(
            "REQUEST" => array(
                "HEAD" => array(
                    "ACCOUNT" => "",
                    "BIZTRANSACTIONID" => "PMS_" . date("YmdHis") . "_" . rand(),
                    "CONSUMER" => 1,
                    "COUNT" => 1,
                    "MODULE" => "",
                    "PAGENUM" => "",
                    "PAGESIZE" => "",
                    "PASSWORD" => "",
                    "SRVLEVEL" => 1
                ),
                "LIST" => array(
                    "ITEM" => array(
                        "ACCESSTOKEN" => $token,
                        "SYSID" => "10001",
                        "UUID" => $uuid,
                    )
                )
            )

        );
        $xmldata = arr2xml($arr, false);
        try {
            $wsdl = Config::get('app.esb_idm_getuserinfo');
            $xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:idm="http://www.cq-p.com.cn/IDM_USER_01_GetUserInfo">';
            $xml .= "<soapenv:Header/>
					   <soapenv:Body>
						  <idm:IDM_USER_01_GetUserInfo>
						      <idm:DATA><![CDATA[" . $xmldata . "]]></idm:DATA>
                          </idm:IDM_USER_01_GetUserInfo>
					   </soapenv:Body>
					</soapenv:Envelope>";
            $arr_header[] = "Content-type: text/xml"; //使用xml格式传递
            $arr_header[] = 'SOAPAction:http://www.cq-p.com.cn/IDM_USER_01_GetUserInfo'; //添加swdl的方法

            $result = http_request_xml($wsdl, $xml, $arr_header);

            $result = xmltoarray($result);

            wlog('t', $result);

            return $result;

        } catch (\Exception $e) {
            $error = ["status" => false, "msg" => $e->getMessage(), "code" => $e->getCode()];
            return $error;
        }

    }

    //导出
    public function getExcel($expTitle, $expCellName, $expTableData, $str = "")
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle . date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $common = $str;
        $objPHPExcel = new Spreadsheet();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $common);
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), ' ' . $expTableData[$i][$expCellName[$j][0]]);

            }
        }
        foreach ($cellName as $value) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($value)->setWidth(20);

        }
        ob_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $expTitle . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $objWriter->save('php://output');
        $objPHPExcel->disconnectWorksheets();
        unset($objPHPExcel);
        exit();
    }

    /**
     * 向上查找某人的组织树
     * @param $ProjectPerOrgModel
     * @param $orgid
     * @return \think\response\Json
     */
    public function findOrgListUpIteraction($ProjectPerOrgModel, $orgid)
    {
        try {

            global $org_global_up;
            $orglist = $ProjectPerOrgModel->where('id', $orgid)->find();
            if ($orglist['id']) {
                $org_global_up[] = $orglist['id'];
            }
            if ($orglist) {
                $orglist = $orglist->toArray();
                $this->findOrgListUpIteraction($ProjectPerOrgModel, $orglist['pid']);
            }
            return true;

        } catch (\Exception $e) {
            $error = ["status" => false, "msg" => $e->getMessage(), "code" => $e->getCode()];
            return json($error);
        }
    }

    /**
     * 向上查找某人的组织树,只到部门
     * @param $ProjectPerOrgModel
     * @param $orgid
     * @return \think\response\Json
     */
    public function findOrgListUpIteractionToDepart($ProjectPerOrgModel, $orgid)
    {
        try {

            global $org_global_up;
            $orglist = $ProjectPerOrgModel->where('id', $orgid)->where('id', '<>', 3)->find();
            if ($orglist['id'] && $orglist['depart_spot'] == 1) {
                $org_global_up[] = $orglist['id'];
            }
            if ($orglist) {
                $orglist = $orglist->toArray();
                $this->findOrgListUpIteractionToDepart($ProjectPerOrgModel, $orglist['pid']);
            }
            return true;

        } catch (\Exception $e) {
            $error = ["status" => false, "msg" => $e->getMessage(), "code" => $e->getCode()];
            return json($error);
        }
    }

    /**
     * 创建部门月平均分
     * @param $month
     * @param $orgid 顶级id
     * @return array
     */
    public function createDepartAvgScore($month, $orgid)
    {
        try {

            $ProjectReviewResultModel = new ProjectReviewResult();
            $ProjectPerformanceClassModel = new ProjectPerformanceClass();
            $ProjectPerformanceSpotModel = new ProjectPerformanceSpot();
            $ProjectPerformanceModel = new ProjectPerformanceModel();
            $ProjectPerOrgModel = new ProjectPerOrgModel();
            $ProjectLockPerOrgModel = new ProjectLockPerOrg();

            //判断数据是否已经锁定
            $Lockorgcount = $ProjectLockPerOrgModel->where('pid', '=', $orgid)->where('month', '=', $month)->count();
            $sql =  $ProjectLockPerOrgModel->getLastSql();

            $orgArr_tmp = array();
            $where[] = ['pid','=',$orgid];
            $orgArr = $ProjectPerOrgModel->where($where)->select()->toArray();
            $sql1 = $ProjectPerOrgModel->getLastSql();

            if(!$orgArr)  $orgArr_tmp = $ProjectPerOrgModel->where("id","=",$orgid)->select()->toArray();
            $sql2 = $ProjectPerOrgModel->getLastSql();
            if(count($orgArr_tmp)){
                if($orgArr_tmp[0]['depart_spot']) {
                    $orgArr = $orgArr_tmp;
                }
            }

            $orgStr = "";
            foreach ($orgArr as $k => $v) {
                $orgStr = $v['id'] . ',' . $orgStr;
            }
            $orgStrTrim = rtrim($orgStr, ',');
            if(!$orgStrTrim){
                $error = ["status" => false, "msg" => "无对应组织下级组织！"];
                return $error;
            }

            $weight_quality = $ProjectPerformanceClassModel->where('id', '=', 2)->find()->toArray(); //取质量分类得权重
            $spot_quality = $ProjectPerformanceSpotModel->where('weight', '>', 0)->select()->toArray();//取考核标准得权重，有权重值的，按照权重值算出来的分数，加到总分里边
            $spot_quality_arr = "";
            foreach ($spot_quality as $v) {
                $spot_quality_arr = $spot_quality_arr . $v['id'] . ',';
            }
            $spot_quality_arr = rtrim($spot_quality_arr, ",");
            $reviewResultList_quality = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,p.uid,((sum(rw.score*100)/100+100)*' . ($weight_quality["weight"] / 100) . ') as total_score,rw.spot_id')
                ->join('ProjectPerOrgPeople p', 'rw.uid = p.id')
                ->where('org_id', 'IN', $orgStrTrim)
                ->where('rw.month', '=', $month)
                ->where('spot_id', 'NOT IN', "$spot_quality_arr")
                ->where('class_id', '=', 2)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            $sql = $ProjectReviewResultModel->getLastSql();


//            $reviewResultList_weight_quality = $ProjectReviewResultModel->alias('rw')
//                ->field('p.name,p.uid,(sum(rw.score*100*(weight/100))/100) as total_score,rw.spot_id')
//                ->join('ProjectPerOrgPeople p', 'rw.uid = p.id')
//                ->join('project_performance_spot s', 'rw.spot_id = s.id')
//                ->where('org_id', 'IN', $orgStrTrim)
//                ->where('rw.month', '=', $month)
//                ->where('spot_id', 'IN', "$spot_quality_arr")
//                ->where('rw.class_id', '=', 2)
//                ->group('rw.uid')
//                ->select()->toArray(); //只包含考核标准设置了权重值的
            $sql = "select name,uid,(sum(score*100*(100/100))/100) as total_score from".
                "(SELECT p.name,p.uid,max(rw.spot_id) spot_id,max(rw.score) score
            FROM `zt_project_review_result` `rw` 
 INNER JOIN `zt_project_per_org_people` `p` ON `rw`.`uid`=`p`.`id` 
 #INNER JOIN `zt_project_performance_spot` `s` ON `rw`.`spot_id`=`s`.`id` 
 WHERE  `org_id` IN  ($orgStrTrim)
            AND `rw`.`month` = $month
            AND `spot_id` IN  ($spot_quality_arr)
            AND `rw`.`class_id` = 2
            #AND p.`name`= '颜森'
            and rw.spot_id in (206,92)
 group by p.name,p.uid
union all
SELECT p.name,p.uid,rw.spot_id,rw.score 
  FROM `zt_project_review_result` `rw` 
 INNER JOIN `zt_project_per_org_people` `p` ON `rw`.`uid`=`p`.`id` 
 #INNER JOIN `zt_project_performance_spot` `s` ON `rw`.`spot_id`=`s`.`id` 
 WHERE  `org_id` IN ($orgStrTrim)
            AND `rw`.`month` = $month
            AND `spot_id` IN  ($spot_quality_arr)
            AND `rw`.`class_id` = 2
            #AND p.`name`= '颜森'
            and rw.spot_id not in (206,92)) a group by name,uid";
            $reviewResultList_weight_quality = Db::query($sql);
//            $sql = $ProjectReviewResultModel->getLastSql();



            $weight_normal = $ProjectPerformanceClassModel->where('id', '=', 1)->find()->toArray();
            $reviewResultList_normal = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,p.uid,(sum(rw.score*100)*' . ($weight_normal["weight"] / 100) . '/100) as total_score,(sum(rw.score*100)/100) as ordinary_score')
                ->join('ProjectPerOrgPeople p', 'rw.uid = p.id')
                ->where('org_id', 'IN', $orgStrTrim)
                ->where('rw.month', '=', $month)
                ->where('class_id', '=', 1)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            if(!$reviewResultList_normal){
                $error = ["status" => false, "msg" => "暂无可以用数据"];
                return $error;
            }

            if ($reviewResultList_normal) {

                //把质量分加入到日常分里去
                $i = 0;
                foreach ($reviewResultList_normal as $key => $vo) {

                    foreach ($reviewResultList_quality as $k => $v) {
                        if ($v['uid'] == $vo['uid']) {
                            $reviewResultList_normal[$i]['total_score'] = ($reviewResultList_normal[$i]['total_score'] * 100 + $v['total_score'] * 100) / 100;
                        }
                    }
                    $i++;

                }

                //把附加分加进去
                $i = 0;
                foreach ($reviewResultList_normal as $key => $vo) {

                    foreach ($reviewResultList_weight_quality as $k => $v) {
                        if ($v['uid'] == $vo['uid']) {
                            $reviewResultList_normal[$i]['total_score'] = ($reviewResultList_normal[$i]['total_score'] * 100 + $v['total_score'] * 100) / 100;
                        }
                    }
                    $i++;

                }

            }
            if ($reviewResultList_normal)
                $reviewResultList_normal_result = arraySort($reviewResultList_normal, 'total_score', SORT_DESC);

            //当前部门人数
            $reviewResultList_normal_result_count = count($reviewResultList_normal_result);
            //等级对应的人数量
            if ($reviewResultList_normal_result_count >= 10) {
                $Level_A = floor(($reviewResultList_normal_result_count * 0.1));
                $Level_B = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_C = $reviewResultList_normal_result_count - 2 * ($Level_A + $Level_B);
                $Level_D = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_E = floor(($reviewResultList_normal_result_count * 0.1));
            } else if ($reviewResultList_normal_result_count >= 5 && $reviewResultList_normal_result_count < 10) {
                $Level_A = round(($reviewResultList_normal_result_count * 0.1));
                $Level_B = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_C = $reviewResultList_normal_result_count - 2 * ($Level_A + $Level_B);
                $Level_D = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_E = round(($reviewResultList_normal_result_count * 0.1));
            } else if ($reviewResultList_normal_result_count < 5) {
                $error = ["status" => false, "msg" => "该组织人数低于5人，无法生成月评等级信息！"];
                return $error;
            }

            //计算总分
            $t_score = 0;
            $t_num = count($reviewResultList_normal_result);
            foreach ($reviewResultList_normal_result as $rv) {
                $t_score = ($t_score * 100 + $rv['total_score'] * 100) / 100;
            }
            //计算基准分(新增总分排序)
            $i = 0;
            foreach ($reviewResultList_normal_result as $key => $rvo) {
                $reviewResultList_normal_result[$i]['create_time'] = date("Y-m-d H:i", time());
                $reviewResultList_normal_result[$i]['month'] = date("Y-m", $month);
                $reviewResultList_normal_result[$i]['avg_score'] = round($t_score / $t_num, 2);
                $reviewResultList_normal_result[$i]['total_score'] = floatval($rvo['total_score']);
                $reviewResultList_normal_result[$i]['order'] = $key + 1;
                if($key+1<=$Level_A) $reviewResultList_normal_result[$i]['level'] = "A";
                if(($key+1)<=($Level_B+$Level_A) && ($key+1>$Level_A)) $reviewResultList_normal_result[$i]['level'] = "B";
                if(($key+1)<=($Level_C+$Level_B+$Level_A) && ($key+1>$Level_B+$Level_A)) $reviewResultList_normal_result[$i]['level'] = "C";
                if(($key+1)<=($Level_D+$Level_C+$Level_B+$Level_A) && ($key+1>$Level_C+$Level_B+$Level_A)) $reviewResultList_normal_result[$i]['level'] = "D";
                if(($key+1)<=($Level_E+$Level_D+$Level_C+$Level_B+$Level_A) && ($key+1>$Level_D+$Level_C+$Level_B+$Level_A)) $reviewResultList_normal_result[$i]['level'] = "E";
                $reviewResultList_normal_result[$i]['ordinary_score'] = floatval($rvo['ordinary_score']);
                $i++;
            }

            //新增日常分排序
            if ($reviewResultList_normal)
                $reviewResultList_normal_result_tmp = arraySort($reviewResultList_normal, 'ordinary_score', SORT_DESC);

            foreach ($reviewResultList_normal_result_tmp as $k => $v) {
                foreach ($reviewResultList_normal_result as $key => $rvo) {
                    if ($v['uid'] == $rvo['uid']) {
                        $reviewResultList_normal_result[$key]['ordinary_order'] = $k + 1;
                    }
                }
            }
            //构造部门人员id集合
            $peopleArr = "";
            if ($reviewResultList_normal_result) {
                foreach ($reviewResultList_normal_result as $o) {
                    $peopleArr = $o['uid'] . "," . $peopleArr;
                }
            }
            $peopleArr = rtrim($peopleArr, ",");

            //查询是否已有记录，如果有就进行数据更新
            $peopleInfo = $ProjectPerformanceModel->where('uid', 'IN', $peopleArr)->where('month', 'like', date("Y-m", $month))->select()->toArray();

            if ($peopleInfo) {

                $i = 0;
                foreach ($peopleInfo as $vvv) {
                    foreach ($reviewResultList_normal_result as $vvv1) {
                        if ($vvv['uid'] == $vvv1['uid']) {
                            $peopleInfo[$i]['total_score'] = $vvv1['total_score'];
                            $peopleInfo[$i]['avg_score'] = $vvv1['avg_score'];
                            $peopleInfo[$i]['avg_score'] = $vvv1['avg_score'];
                            $peopleInfo[$i]['ordinary_score'] = $vvv1['ordinary_score'];
                        }
                    }
                    $i++;
                }
                //更新总分排名
                $peopleInfo = arraySort($peopleInfo, 'total_score', SORT_DESC);
                foreach ($peopleInfo as $k => $vsort) {
                    if($k+1<=$Level_A) $peopleInfo[$k]['level'] = "A";
                    if(($k+1)<=($Level_B+$Level_A) && ($k+1>$Level_A)) $peopleInfo[$k]['level'] = "B";
                    if(($k+1)<=($Level_C+$Level_B+$Level_A) && ($k+1>$Level_B+$Level_A)) $peopleInfo[$k]['level'] = "C";
                    if(($k+1)<=($Level_D+$Level_C+$Level_B+$Level_A) && ($k+1>$Level_C+$Level_B+$Level_A)) $peopleInfo[$k]['level'] = "D";
                    if(($k+1)<=($Level_E+$Level_D+$Level_C+$Level_B+$Level_A) && ($k+1>$Level_D+$Level_C+$Level_B+$Level_A)) $peopleInfo[$k]['level'] = "E";
                    $peopleInfo[$k]['order'] = $k + 1;
                    $peopleInfo[$k]['update_time'] = date('Y-m-d H:i:s',time());
                }
                //更新日常分排名
                $peopleInfo = arraySort($peopleInfo, 'ordinary_score', SORT_DESC);
                foreach ($peopleInfo as $k => $vsort) {
                    $peopleInfo[$k]['ordinary_order'] = $k + 1;
                }

                if (!$Lockorgcount) {
                    $ProjectPerformanceModel->saveAll($peopleInfo);
                    $error = ["status" => true, "msg" => "数据更新成功"];
                    return $error;
                } else {
                    $error = ["status" => false, "msg" => "数据已锁定，不能修改"];
                    return $error;
                }//批量更新
            } else {
                if (!$Lockorgcount) {
                    $ProjectPerformanceModel->insertAll($reviewResultList_normal_result);
                    $error = ["status" => true, "msg" => "数据新增成功"];
                    return $error;
                } else {
                    $error = ["status" => false, "msg" => "数据已锁定，不能修改"];
                    return $error;
                }//批量插入
            }


        } catch (\Exception $e) {
            $error = ["status" => false, "msg" => $e->getMessage(), "code" => $e->getCode()];
            return $error;
        }
    }

    /**
     * 创建部门月平均分(数据来源历史表)
     * @param $month
     * @param $orgid 顶级id
     * @return array
     */
    public function createOldDepartAvgScore($month, $orgid)
    {
        try {

            $ProjectReviewResultModel = new ProjectLockReviewResult();
            $ProjectPerformanceClassModel = new ProjectLockPerformanceClass();
            $ProjectPerformanceSpotModel = new ProjectLockPerformanceSpot();
            $ProjectPerformanceModel = new ProjectPerformanceModel();
            $ProjectLockPerOrgModel = new ProjectLockPerOrg();
            $month = strtotime($month);

            //判断数据是否已经锁定
            $Lockorgcount = $ProjectPerformanceModel->where('month', '=', date('Y-m',$month))->count();
            $Lockorgcount = false;

            $orgArr = $ProjectLockPerOrgModel->where('month', '=', $month)->where('pid', '=', $orgid)->select()->toArray();
            $orgStr = "";
            foreach ($orgArr as $k => $v) {
                $orgStr = $v['id'] . ',' . $orgStr;
            }
            $orgStrTrim = rtrim($orgStr, ',');

            $weight_quality = $ProjectPerformanceClassModel->where('month', '=', $month)->where('id', '=', 2)->find()->toArray(); //取质量分类得权重
            $spot_quality = $ProjectPerformanceSpotModel->where('month', '=', $month)->where('weight', '>', 0)->select()->toArray();//取考核标准得权重，有权重值的，按照权重值算出来的分数，加到总分里边
            $spot_quality_arr = "";
            foreach ($spot_quality as $v) {
                $spot_quality_arr = $spot_quality_arr . $v['id'] . ',';
            }
            $spot_quality_arr = rtrim($spot_quality_arr, ",");
            $reviewResultList_quality = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,p.uid,((sum(rw.score*100)/100+100)*' . ($weight_quality["weight"] / 100) . ') as total_score')
                ->join('ProjectLockPerOrgPeople p', 'rw.uid = p.id')
                ->where('org_id', 'IN', $orgStrTrim)
                ->where('rw.month', '=', $month)
                ->where('p.month', '=', $month)
                ->where('spot_id', 'NOT IN', "$spot_quality_arr")
                ->where('class_id', '=', 2)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            $sql = $ProjectReviewResultModel->getLastSql();

//            $reviewResultList_weight_quality = $ProjectReviewResultModel->alias('rw')
//                ->field('p.name,p.uid,(sum(rw.score*100*(weight/100))/100) as total_score')
//                ->join('ProjectPerOrgPeople p', 'rw.uid = p.id')
//                ->join('project_performance_spot s', 'rw.spot_id = s.id')
//                ->where('org_id', 'IN', $orgStrTrim)
//                ->where('rw.month', '=', $month)
//                ->where('spot_id', 'IN', "$spot_quality_arr")
//                ->where('rw.class_id', '=', 2)
//                ->group('rw.uid')
//                ->select()->toArray(); //只包含考核标准设置了权重值的
//
//            $sql = $ProjectReviewResultModel->getLastSql();


            $sql = "select name,uid,(sum(score*100*(100/100))/100) as total_score from".
                "(SELECT p.name,p.uid,max(rw.spot_id) spot_id,max(rw.score) score
            FROM `zt_project_lock_review_result` `rw` 
 INNER JOIN `zt_project_lock_per_org_people` `p` ON `rw`.`uid`=`p`.`id` 
 #INNER JOIN `zt_project_lock_performance_spot` `s` ON `rw`.`spot_id`=`s`.`id` 
 WHERE  `org_id` IN  ($orgStrTrim)
            AND `rw`.`month` = $month
            AND `p`.`month` = $month
            AND `spot_id` IN  ($spot_quality_arr)
            AND `rw`.`class_id` = 2
            #AND p.`name`= '颜森'
            and rw.spot_id in (206,92)
 group by p.name,p.uid
union all
SELECT p.name,p.uid,rw.spot_id,rw.score 
  FROM `zt_project_lock_review_result` `rw` 
 INNER JOIN `zt_project_lock_per_org_people` `p` ON `rw`.`uid`=`p`.`id` 
 #INNER JOIN `zt_project_lock_performance_spot` `s` ON `rw`.`spot_id`=`s`.`id` 
 WHERE  `org_id` IN ($orgStrTrim)
            AND `rw`.`month` = $month
            AND `p`.`month` = $month
            AND `spot_id` IN  ($spot_quality_arr)
            AND `rw`.`class_id` = 2
            #AND p.`name`= '颜森'
            and rw.spot_id not in (206,92)) a group by name,uid";
            wlog('ssql',$sql);
            $reviewResultList_weight_quality = Db::query($sql);

            $weight_normal = $ProjectPerformanceClassModel->where('month', '=', $month)->where('id', '=', 1)->find()->toArray();
            $reviewResultList_normal = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,p.uid,(sum(rw.score*100)*' . ($weight_normal["weight"] / 100) . '/100) as total_score,(sum(rw.score*100)/100) as ordinary_score')
                ->join('ProjectLockPerOrgPeople p', 'rw.uid = p.id')
                ->where('org_id', 'IN', $orgStrTrim)
                ->where('rw.month', '=', $month)
                ->where('p.month', '=', $month)
                ->where('class_id', '=', 1)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            if ($reviewResultList_normal) {

                //把质量分加入到日常分里去
                $i = 0;
                foreach ($reviewResultList_normal as $key => $vo) {

                    foreach ($reviewResultList_quality as $k => $v) {
                        if ($v['uid'] == $vo['uid']) {
                            $reviewResultList_normal[$i]['total_score'] = ($reviewResultList_normal[$i]['total_score'] * 100 + $v['total_score'] * 100) / 100;
                        }
                    }
                    $i++;

                }

                //把附加分加进去
                $i = 0;
                foreach ($reviewResultList_normal as $key => $vo) {

                    foreach ($reviewResultList_weight_quality as $k => $v) {
                        if ($v['uid'] == $vo['uid']) {
                            $reviewResultList_normal[$i]['total_score'] = ($reviewResultList_normal[$i]['total_score'] * 100 + $v['total_score'] * 100) / 100;
                        }
                    }
                    $i++;

                }


            }
            if ($reviewResultList_normal)
                $reviewResultList_normal_result = arraySort($reviewResultList_normal, 'total_score', SORT_DESC);

            //当前部门人数
            $reviewResultList_normal_result_count = count($reviewResultList_normal_result);
            //等级对应的人数量
            if ($reviewResultList_normal_result_count >= 10) {
                $Level_A = floor(($reviewResultList_normal_result_count * 0.1));
                $Level_B = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_C = $reviewResultList_normal_result_count - 2 * ($Level_A + $Level_B);
                $Level_D = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_E = floor(($reviewResultList_normal_result_count * 0.1));
            } else if ($reviewResultList_normal_result_count >= 5 && $reviewResultList_normal_result_count < 10) {
                $Level_A = round(($reviewResultList_normal_result_count * 0.1));
                $Level_B = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_C = $reviewResultList_normal_result_count - 2 * ($Level_A + $Level_B);
                $Level_D = floor(($reviewResultList_normal_result_count * 0.3));
                $Level_E = round(($reviewResultList_normal_result_count * 0.1));
            } else if ($reviewResultList_normal_result_count < 5) {
                $error = ["status" => false, "msg" => "该组织人数低于5人，无法生成月评等级信息！"];
                return $error;
            }

            //计算总分
            $t_score = 0;
            $t_num = count($reviewResultList_normal_result);
            foreach ($reviewResultList_normal_result as $rv) {
                $t_score = ($t_score * 100 + $rv['total_score'] * 100) / 100;
            }
            //计算基准分(新增总分排序)
            $i = 0;
            foreach ($reviewResultList_normal_result as $key => $rvo) {
                $reviewResultList_normal_result[$i]['create_time'] = date("Y-m-d H:i", time());
                $reviewResultList_normal_result[$i]['month'] = date("Y-m", $month);
                $reviewResultList_normal_result[$i]['avg_score'] = round($t_score / $t_num, 2);
                $reviewResultList_normal_result[$i]['total_score'] = floatval($rvo['total_score']);
                $reviewResultList_normal_result[$i]['order'] = $key + 1;
                if($key+1<=$Level_A) $reviewResultList_normal_result[$i]['level'] = "A";
                if(($key+1)<=($Level_B+$Level_A) && ($key+1>$Level_A)) $reviewResultList_normal_result[$i]['level'] = "B";
                if(($key+1)<=($Level_C+$Level_B+$Level_A) && ($key+1>$Level_B+$Level_A)) $reviewResultList_normal_result[$i]['level'] = "C";
                if(($key+1)<=($Level_D+$Level_C+$Level_B+$Level_A) && ($key+1>$Level_C+$Level_B+$Level_A)) $reviewResultList_normal_result[$i]['level'] = "D";
                if(($key+1)<=($Level_E+$Level_D+$Level_C+$Level_B+$Level_A) && ($key+1>$Level_D+$Level_C+$Level_B+$Level_A)) $reviewResultList_normal_result[$i]['level'] = "E";
                $reviewResultList_normal_result[$i]['ordinary_score'] = floatval($rvo['ordinary_score']);
                $i++;
            }

            //新增日常分排序
            if ($reviewResultList_normal)
                $reviewResultList_normal_result_tmp = arraySort($reviewResultList_normal, 'ordinary_score', SORT_DESC);

            foreach ($reviewResultList_normal_result_tmp as $k => $v) {
                foreach ($reviewResultList_normal_result as $key => $rvo) {
                    if ($v['uid'] == $rvo['uid']) {
                        $reviewResultList_normal_result[$key]['ordinary_order'] = $k + 1;
                    }
                }
            }
            //构造部门人员id集合
            $peopleArr = "";
            if ($reviewResultList_normal_result) {
                foreach ($reviewResultList_normal_result as $o) {
                    $peopleArr = $o['uid'] . "," . $peopleArr;
                }
            }
            $peopleArr = rtrim($peopleArr, ",");

            //查询是否已有记录，如果有就进行数据更新
            $peopleInfo = $ProjectPerformanceModel->where('uid', 'IN', $peopleArr)->where('month', 'like', date("Y-m", $month))->select()->toArray();

            if ($peopleInfo) {

                $i = 0;
                foreach ($peopleInfo as $vvv) {
                    foreach ($reviewResultList_normal_result as $vvv1) {
                        if ($vvv['uid'] == $vvv1['uid']) {
                            $peopleInfo[$i]['total_score'] = $vvv1['total_score'];
                            $peopleInfo[$i]['avg_score'] = $vvv1['avg_score'];
                            $peopleInfo[$i]['avg_score'] = $vvv1['avg_score'];
                            $peopleInfo[$i]['ordinary_score'] = $vvv1['ordinary_score'];
                        }
                    }
                    $i++;
                }
                //更新总分排名
                $peopleInfo = arraySort($peopleInfo, 'total_score', SORT_DESC);
                foreach ($peopleInfo as $k => $vsort) {
                    if($k+1<=$Level_A) $peopleInfo[$k]['level'] = "A";
                    if(($k+1)<=($Level_B+$Level_A) && ($k+1>$Level_A)) $peopleInfo[$k]['level'] = "B";
                    if(($k+1)<=($Level_C+$Level_B+$Level_A) && ($k+1>$Level_B+$Level_A)) $peopleInfo[$k]['level'] = "C";
                    if(($k+1)<=($Level_D+$Level_C+$Level_B+$Level_A) && ($k+1>$Level_C+$Level_B+$Level_A)) $peopleInfo[$k]['level'] = "D";
                    if(($k+1)<=($Level_E+$Level_D+$Level_C+$Level_B+$Level_A) && ($k+1>$Level_D+$Level_C+$Level_B+$Level_A)) $peopleInfo[$k]['level'] = "E";
                    $peopleInfo[$k]['order'] = $k + 1;
                    $peopleInfo[$k]['update_time'] = date('Y-m-d H:i:s',time());
                }
                //更新日常分排名
                $peopleInfo = arraySort($peopleInfo, 'ordinary_score', SORT_DESC);
                foreach ($peopleInfo as $k => $vsort) {
                    $peopleInfo[$k]['ordinary_order'] = $k + 1;
                }

                if (!$Lockorgcount) {
                    $ProjectPerformanceModel->saveAll($peopleInfo);
                    $error = ["status" => true, "msg" => "数据更新成功"];
                    return $error;
                } else {
                    $error = ["status" => false, "msg" => "数据已锁定，不能修改"];
                    return $error;
                }//批量更新
            } else {
                if (!$Lockorgcount) {
                    $ProjectPerformanceModel->insertAll($reviewResultList_normal_result);
                    $error = ["status" => true, "msg" => "数据新增成功"];
                    return $error;
                } else {
                    $error = ["status" => false, "msg" => "数据已锁定，不能修改"];
                    return $error;
                }//批量插入
            }


        } catch (\Exception $e) {
            $error = ["status" => false, "msg" => $e->getMessage(), "code" => $e->getCode()];
            return $error;
        }

    }

}